package com.qihoo.finance.lcs.enhance.threadpool;

import com.qihoo.finance.msf.core.context.ContextLog4j2Util;
import com.qihoo.finance.msf.core.context.ServiceContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

public class WorkContext implements Runnable {
    private static final Logger LOGGER = LogManager.getLogger(WorkContext.class);

    private static final String MSF_CONTEXT_VAR_REQUEST_NO = "requestNo";

    private WorkUnit workUnit;
    private String mainRequestNo;
    private Thread mainThread;
    private Map<String, String> contextVar;
    private String workSeqNo = null;

    public WorkContext(WorkUnit workUnit, String workSeqNo) {
        if (null == workUnit) {
            throw new IllegalArgumentException("workUnit不得为空");
        }
        this.workUnit = workUnit;

        mainThread = Thread.currentThread();

        ServiceContext serviceContext = ServiceContext.getContext();
        this.mainRequestNo = serviceContext.getRequestNo();

        Map<String, String> msfContextVar = serviceContext.getContextVar();
        if (null == msfContextVar || msfContextVar.size() == 0) {
            contextVar = new HashMap<>();
        } else {
            this.contextVar = new HashMap<>(msfContextVar);
        }

        if (null != workSeqNo) {
            this.workSeqNo = workSeqNo;
        }
    }

    @Override
    public void run() {
        ServiceContext context = ServiceContext.getContext();
        try {
            if (null != context) {
                if (null != workSeqNo) {
                    String newRequestNo = mainRequestNo + "-" + workSeqNo;
                    contextVar.put(MSF_CONTEXT_VAR_REQUEST_NO, newRequestNo);
                }
                context.addContextVar(contextVar);
                ContextLog4j2Util.addContext2MDC();
            }
            workUnit.run();
        } catch (Exception e) {
            LOGGER.error("线程池任务执行异常", e);
        } finally {
            if (null != context) {
                if (Thread.currentThread().equals(mainThread)) {//caller runs
                    if (null != mainRequestNo) {
                        context.setRequestNo(mainRequestNo);
                        ContextLog4j2Util.addContext2MDC();
                    }
                } else {
                    context.getContextVar().clear();
                }
            }
        }
    }
}
